package com.beverages.orders.config;

import feign.Client;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Retryer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignOkHttpConfig {

    // 注入 OkHttpConfig
    private final OkHttpConfig okHttpConfig;

    private static final Logger logger = LoggerFactory.getLogger(FeignOkHttpConfig.class);

    // 构造函数注入 OkHttpConfig
    public FeignOkHttpConfig(OkHttpConfig okHttpConfig) {
        this.okHttpConfig = okHttpConfig;
    }

    @Bean
    public Client feignClient() {
        // 使用 OkHttpConfig 中的 OkHttpClient 配置
        okhttp3.OkHttpClient okHttpClient = okHttpConfig.okHttpClient();
        return new feign.okhttp.OkHttpClient(okHttpClient);  // 返回 Feign 使用的 OkHttpClient
    }

    // 配置 Feign 使用自定义的重试策略
    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(1000, 5000, 3);  // 初始间隔1秒，最大间隔5秒，重试3次
    }

    // 配置 RequestInterceptor，确保 Feign 请求中带有 X-Feign-Request 请求头
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                logger.info("Adding X-Feign-Request header to Feign request");
                template.header("X-Feign-Request", "true");  // 为每个 Feign 请求添加 X-Feign-Request 请求头
            }
        };
    }
}